import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

import org.xml.sax.SAXException;

import com.aetrion.flickr.*;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

public class UploadFrame extends javax.swing.JFrame {
    
    /** Creates new form UploadFrame */
    public UploadFrame(Picture _pic,Flickr _myFlickr, Object _uploadSync) {
        uploadSync = _uploadSync;
    	pic = _pic;
        myFlickr = _myFlickr;
    	initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        viewPane = new javax.swing.JEditorPane();
        UploadButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tagTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        PictureScrollPane = new javax.swing.JScrollPane();
        pictureLabel = new javax.swing.JLabel();
        isPublicCheckBox = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        titleTextField = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        boldMI = new javax.swing.JMenuItem();
        italicMI = new javax.swing.JMenuItem();
        underlinedMI = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Upload Picture");

        PictureScrollPane.setAutoscrolls(true);
        PictureScrollPane.setMaximumSize(new java.awt.Dimension(749, 251));
        
        pictureLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
      	try {
			pictureLabel.setIcon(new ImageIcon(pic.getURI().toURL()));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		PictureScrollPane.setViewportView(pictureLabel);
		
        tagTextField.setText(pic.getTags());
		
        titleTextField.setText(pic.toString());
        
        viewPane.setContentType("text/html");
        viewPane.setText(pic.getHTML());
        jScrollPane1.setViewportView(viewPane);

        UploadButton.setText("Upload");
        UploadButton.addActionListener(new UploadListener(this));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Description:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Tags:");
        
        isPublicCheckBox.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        isPublicCheckBox.setText("Public?: ");
        isPublicCheckBox.setSelected(true);
        isPublicCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        
        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Title:");

        jMenu1.setText("Style");
       
        boldMI.setText("Bold");
        boldMI.setAction(new StyledEditorKit.BoldAction());
        boldMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK));
        jMenu1.add(boldMI);

        italicMI.setText("Italicize");
        italicMI.setAction(new StyledEditorKit.ItalicAction());
        italicMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenu1.add(italicMI);

        underlinedMI.setText("Underlined");
        underlinedMI.setAction(new StyledEditorKit.UnderlineAction());
        underlinedMI.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_U, java.awt.event.InputEvent.CTRL_MASK));
        jMenu1.add(underlinedMI);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
                    .addComponent(PictureScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 749, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tagTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE))
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(titleTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(isPublicCheckBox))
                    .addComponent(UploadButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PictureScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(isPublicCheckBox)
                    .addComponent(titleTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tagTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(UploadButton)
                .addContainerGap())
        );


        pack();
    }// </editor-fold>

    public static String cleanUp(String text)
    {
    	String cleantext = text;
    	//System.out.println(cleantext);
    	cleantext = cleantext.replaceAll("<br/>", "<br>");
    	cleantext = cleantext.replaceAll("</?html>|</?head>|</?body>|<p>", "");
    	cleantext = cleantext.replaceAll("</p>", "<br>");
    	cleantext = cleantext.replaceAll("(<br>\\p{Blank}*<br>\\p{Blank}*)+","<br>");
    	cleantext = cleantext.replaceAll("<br>", "\n");
    	cleantext = cleantext.replaceAll("(\\p{Blank}*\n\\p{Blank}*){2,}","\n");
    	cleantext = cleantext.replaceAll("\\p{Blank}{2,}", " ");
    	//System.out.println(cleantext.trim());
    	return cleantext.trim();
    }
    
    public class UploadListener implements ActionListener
    {
    	UploadFrame parent;
    	public UploadListener(UploadFrame _parent)
    	{
    		parent = _parent;
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		synchronized (uploadSync)
    		{
	    		UploadMetaData picData = new UploadMetaData();
	    		
	    		picData.setTitle(titleTextField.getText().trim());
	    		
	    		String[] tags = tagTextField.getText().trim().split(" ");
	    		ArrayList<String> tagCollection = new ArrayList<String>();
	    		for(String tag : tags)
	    			tagCollection.add(tag);
	    		picData.setTags(tagCollection);
	    		
	    		picData.setHidden(!isPublicCheckBox.isSelected());
	    		picData.setPublicFlag(isPublicCheckBox.isSelected());
	    		picData.setDescription(cleanUp(viewPane.getText()));
	    		
	    		FileInputStream input = null;
	    		try {
					input = new FileInputStream(new File(pic.getURI()));
				} catch (FileNotFoundException e1) {
					JOptionPane.showMessageDialog(parent,"The picture was not found at: " + pic.getURI(),"Cant't Find Photo!",JOptionPane.ERROR_MESSAGE);
					return;
				}
	    		
	    		Uploader uploader = new Uploader(myFlickr.getApiKey(),myFlickr.getTransport());
	    		
	    		try {
					uploader.upload(input, picData);
					JOptionPane.showMessageDialog(parent,"Upload Succeeded!","Success!", JOptionPane.INFORMATION_MESSAGE);
				} catch (Exception exception)
				{
					JOptionPane.showMessageDialog(parent,"Upload Failed:\n" + exception.getMessage(), "Upload Failed!", JOptionPane.ERROR_MESSAGE);
					return;
				}
				parent.setVisible(false);
				parent.dispose();
    		}
    	}
    }
    
    // Variables declaration - do not modify
    private javax.swing.JScrollPane PictureScrollPane;
    private javax.swing.JButton UploadButton;
    private javax.swing.JMenuItem boldMI;
    private javax.swing.JCheckBox isPublicCheckBox;
    private javax.swing.JMenuItem italicMI;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField tagTextField;
    private javax.swing.JTextField titleTextField;
    private javax.swing.JMenuItem underlinedMI;
    private javax.swing.JEditorPane viewPane;
    private javax.swing.JLabel pictureLabel;
    private Flickr myFlickr;
    private Picture pic;
    private Object uploadSync;
    // End of variables declaration
    
}
